package com.fl.message.wb;


import com.alibaba.fastjson.JSON;
import com.fl.message.entity.UserMessage;
import com.fl.message.mq.RabbitmqReceive;
import com.fl.message.util.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import static com.fl.message.constant.MessageConstant.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: fulin
 * @Date: 2023/01/06/11:28
 * @Description:
 */
@ServerEndpoint("/opinion/message/{clientId}/{type}")
@Component
public class OpinionSocketServer {


    public static ConcurrentHashMap<String, OpinionSocketServer> customerSet = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, OpinionSocketServer> serverSet = new ConcurrentHashMap<>();
    public static List<UserMessage> pendingMessage = new ArrayList<>();


    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam("clientId") String clientId, @PathParam("type") String type) throws IOException {
        this.session = session;
        if (CUSTOMER.equals(type)) {
            customerSet.put(clientId, this);
        } else if (SERVER.equals(type)) {
            serverSet.put(clientId, this);
            initServer(this.session, clientId);
        }
    }

    public void initServer(Session session, String clientId) {
        RabbitmqReceive rabbitmqReceive = SpringContextUtil.getBean(RabbitmqReceive.class);
        pendingMessage.stream().forEach(data -> {
            String messageTips = "用户" + clientId + "为您服务,正在查看您的留言";
            data.setToId(clientId);
            UserMessage userMessage = new UserMessage(data.getFormId(),data.getToId(),data.getMessage(),data.getType());
            //客户提示
            if (rabbitmqReceive.consumerPendingMessage(userMessage, messageTips)) {
                //工作人员查看信息
                session.getAsyncRemote().sendText(JSON.toJSONString(data));
            }
        });

    }

    public void sendMessage(UserMessage userMessage) {
        String message = JSON.toJSONString(userMessage);
        this.session.getAsyncRemote().sendText(message);
    }

    @OnMessage
    public void onMessage(String message, Session session) {

    }
}

